<template>
  <div>
    <p>登录 注册</p>
    <p><input type="text" placeholder="请输入用户名" v-model="info.name" /></p>
    <p><input type="text" placeholder="请输入密码" v-model="info.pwd" /></p>
    <div v-html="str" @click="getcaptchas"></div>
    <p @click="getcaptchas">点击更新验证码</p>
    <p>
      <input type="text" placeholder="请输入验证码" v-model="info.captcha" />
    </p>
    <p>
      <button @click="loginto">登录</button>
      <button @click="registerto">注册</button>
    </p>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { login, register, getcaptcha } from "../../api/api";
import { useRouter } from "vue-router";

const router = useRouter();

// 数据
const info = ref({
  name: "",
  pwd: "",
  captcha: "",
});

let str = ref("");

onMounted(() => {
  render();
});

const render = () => {
  getcaptcha().then((res) => {
    // console.log(res);
    str.value = res.data;
  });
};

// 点击更新验证码
const getcaptchas = () => {
  render();
};

// 点击登录
const loginto = () => {
  login(info.value.name, info.value.pwd, info.value.captcha).then((res) => {
    if (res.data.code == 1) {
      alert("用户名不存在 请先注册");
    }
    if (res.data.code == 2) {
      alert("密码不正确 请重新输入");
    }
    if (res.data.code == 0) {
      alert("验证码不一致");
    }
    if (res.data.code == 3) {
      let token = res.data.token;
      localStorage.setItem("token", token);
      router.push("/home");
    }
  });
};

// 点击注册
const registerto = () => {
  register(info.value.name, info.value.pwd).then((res) => {
    if (res.data.code == 5) {
      alert("用户已存在 请重新输入");
    }
    if (res.data.code == 6) {
      alert("注用成功！请登录");
    }
  });
};
</script>

<style scoped>
</style>